<?php
/**
 * Created by PhpStorm.
 * User: Auser
 * Date: 2017/5/24
 * Time: 13:28
 */

namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\WxComponentHelper;
use App\Services\IdEncryptService;
use Illuminate\Support\Facades\DB;
use AdminEvaluateService;
use SendTplUserService;
use TestingConfig;
use ParamConfig;
use App\Services\APIUtil;
class WxComponentController extends Controller
{

    public function criclePath($tplid,$appid){
        $arrar = [
            'food'=>ParamConfig::getValue("food_remind_tpl_redirect_".$tplid)."__appid-".$appid,
            'sport'=>ParamConfig::getValue("sport_remind_tpl_redirect_".$tplid)."__appid-".$appid,
        ];
        return apiSuccess($arrar);
    }
    /**结果页，点击确认转发请求发送模板消息
     * @param $uid
     * @param $appid
     */
    public function sendTemplate($uid,$appidEncode,$tplid){
            //返回模板消息，post数据包
            $appid = base64_decode($appidEncode);
            $uid = IdEncryptService::encryption($uid,'decode');
            //模板消息跳转路径
            $request =  TestingConfig::getValue('wechat.dw.callback.url');
        /*//发送饮食模板消息
            $datafood = [
                'redirect'=>ParamConfig::getValue("food_remind_tpl_redirect_".$tplid)."__appid-".$appidEncode,
                'first'=>"邀您参加饮食打卡计划",
                'keyword1'=>"饮食打卡",
                'keyword2'=>date("Y-m-d H:i:s",time()),
                'remark'=>"查看详情"
            ];
            $package = WxComponentHelper::getTemplate($uid[0],$appid,$datafood);
            WxComponentHelper::sendTemplate($package,$appid,$tplid);*/
            //发送跳转模板消息
            $datasport = [
                'redirect'=>$request."appid=".$appidEncode."&tid=".$tplid,
                'first'=>"您的专职营养师提醒您打卡了~",
                'keyword1'=>"饮食、运动打卡",
                'keyword2'=>date("Y-m-d H:i:s",time()),
                'remark'=>"打卡链接：".$request."appid=".$appidEncode."&tid=".$tplid
            ];
            $package = WxComponentHelper::getTemplate($uid[0],$appid,$datasport);
            WxComponentHelper::sendTemplate($package,$appid,$tplid);
    }

    /**用户打卡评价
     * @param Request $request
     */
    public function evaluate(Request $request){
        //答题记录id
        $id = $request->input('id');
        $tid = $request->input('tid');
        $uid = $request->input('uid');
        $time = $request->input('time');
        $appid =  $request->input('appid');
        $eid = $request->input('eid');
        $admin = $request->input('admin');
        $detailId = $request->input('detailid');
        $custom = $request->input('custom');//自定义评价
        if($detailId){//跳转打卡详情http://qatest.qiezilife.com/m/circle_detail/detail_id-161312
            //$redirect=ParamConfig::getValue("food_evaluate_tpl_redirect_cricle_info").$detailId;
            $redirect=ParamConfig::getValue("food_evaluate_tpl_redirect_cricle_info").$detailId."__appid-".base64_encode($appid);

        }else{//跳转个人中心http://qatest.qiezilife.com/m/people/34194
            //$redirect=ParamConfig::getValue("food_evaluate_tpl_redirect_user_info").$uid;
            $redirect =ParamConfig::getValue("food_evaluate_tpl_redirect_user_info")."__appid-".base64_encode($appid);
        }
        $data['uid'] =$uid;
        $data['eid'] = empty($eid)? 0 :$eid;
        $data['custom']=$custom;
        $data['created_at'] = $time;
        $data['dialogue_time'] = date("Y-m-d H:i:s",time());
        AdminEvaluateService::store($data);
        //获取模板id
        if($eid){
            $param = ParamConfig::getById($eid);
        }
        $datasport = [
            'redirect'=>$redirect,
            'first'=>"营养师刚刚评价了您(".$time.")的饮食打卡",
            'keyword1'=>"营养师".$admin,
            'keyword2'=>empty($eid) ? $custom:$param['value'],
            'remark'=>date("Y-m-d H:i:s",time())
        ];
        $package = WxComponentHelper::getTemplate($uid,$appid,$datasport);
        $tplid = ParamConfig::getValue("evaluate_tpl_id");
        WxComponentHelper::sendTemplate($package,$appid,$tplid);
        //存储成功跳转到减脂平台页面
        $base_url = TestingConfig::getValue('website_url');
        $url = $base_url."/admin/testing/decrease/user/info/".$id."/".$tid."/".base64_encode($appid)."/".$time;
        redirectToUrl($url);
    }

    /**定时发送模板消息
     * @param $appid 非加密第三方appid
     * @param $tid   非加密tid
     * @param $tplid
     */
    public function timingSendTpl($appid,$tid,$tplid){
        $users = SendTplUserService::getByAppid($appid,$tid);
        if($users){
            $sendUser = $this->checkCricle($users);
            if($sendUser){
                foreach($sendUser as $v){
                    $uid = IdEncryptService::encryption($v,'encode');
                    $this->sendTemplate($uid,base64_encode($appid),$tplid);
                }
            }
        }
    }


    /**根据开始打卡用户集查找未在今日打卡用户，返回用户组
     * @param $uidArr
     * @return array
     */
    protected function checkCricle($uidArr){
        $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
        $endToday= mktime(23,59,59,date('m'),date('d'),date('Y'));
        $wenda = DB::connection('wenda');
        $usersfood = $wenda->table("qz_circle_detail")
            ->select("published_id")
            ->where('action_type','punch')
            ->where('circle_id',11)
            ->whereBetween('add_time',[$beginToday,$endToday])
            ->whereIn('published_id', $uidArr)
            ->get();
        $userssport = $wenda->table("qz_circle_detail")
            ->select("published_id")
            ->where('action_type','punch')
            ->where('circle_id',12)
            ->whereBetween('add_time',[$beginToday,$endToday])
            ->whereIn('published_id', $uidArr)
            ->get();
        $foodArr = [];
        $sportArr = [];
        foreach($usersfood as $k => $v){
            $foodArr[$k] = $v->{'published_id'};

        }
        foreach($userssport as $k => $v){
            $sportArr[$k] = $v->{'published_id'};
        }
        $haveTwo = array_intersect($sportArr,$foodArr);
        $haveNoTwo = array_diff($uidArr,$haveTwo);
        return $haveNoTwo;
    }


    /**
     * 插入需要定时发送模板消息用户
     */
    public function StartSendTplUser(Request $request){
        $data["uid"] = $request->input('uid');
        $data['tid']= $request->input('tid');
        $data['appid'] = $request->input('appid');
        $data['is_start']  =(int) $request->input('is_start');
        $data['start_time'] = date('Y-m-d H:i:s',time());
        $url = base64_decode($request->input('url'));
        $res = SendTplUserService::storeUser($data);
        //模板id，可以根据不同授权公众号需求定制不同模板消息
        $tplid = ParamConfig::getValue("remind_tpl_id");
        if($res){
            //第一次手动发送模板消息
            $uid = IdEncryptService::encryption($data["uid"],'encode');
            $this->sendTemplate($uid,base64_encode($data['appid']),$tplid);
            redirectToUrl($url);
        }else{
            //手动开始发送模板消失失败
            redirectToUrl($url);
        }
    }

    /**结束发送模板消息，更新数据
     * @param Request $request
     */
    public function EndSendTplUser(Request $request){
        $data["uid"] = $request->input('uid');
        $data['tid']= $request->input('tid');
        $data['appid'] = $request->input('appid');
        $data['is_start']  =(int) $request->input('is_start');
        $data['end_time'] = date('Y-m-d H:i:s',time());
        $url = base64_decode($request->input('url'));
        SendTplUserService::updateStatus($data);
        redirectToUrl($url);
    }




}